package cn.itsource.org.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.org.domain.User;
import cn.itsource.org.mapper.UserMapper;
import cn.itsource.org.query.UserQuery;
import cn.itsource.org.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public int deleteByPrimaryKey(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public void insert(User u) {
        if (u.getId()==null){
            //动态生成盐值
            String s = RandomUtil.randomString(20);
            u.setSalt(s);
            u.setPassword(SecureUtil.md5(u.getPassword()+u.getSalt()));
            userMapper.insert(u);
        }else {
            System.out.println("用户已存在");
        }
    }


    @Override
    @Transactional
    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public void updateByPrimaryKeySelective(User u) {
        if (u.getId() != null) {
            userMapper.updateByPrimaryKeySelective(u);
        }

    }




    @Override
    public PageInfo<User> pageInfo(UserQuery userQuery) {
        PageHelper.startPage(userQuery.getCurrentPage(), userQuery.getPageSize());
        List<User> all = userMapper.getAll(userQuery);
        return new PageInfo<User>(all);
    }

    @Override
    @Transactional
    public void deleteAll(List<User> u) {
        userMapper.deleteAll(u);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        userMapper.delete(id);
    }

    @Override
    public Boolean existsByUsername(User username) {
        String userName = username.getUserName();
        User exits = userMapper.exits(userName);
        if (username.getId()==null){
            if (exits != null){
                if (exits.getUserName().equals(userName)){
                    return true;
                }else {
                    return false;
                }
            }
            return false;
        }else {
            if (exits != null){
                return !exits.getId().equals(username.getId());
            }
            return null;
        }
    }


}
